<template>
  <div class="asset-export">
    <el-card class="export-card">
      <template #header>
        <div class="card-header">
          <span>数据导出</span>
        </div>
      </template>
      
      <el-form :model="exportForm" label-width="120px" class="export-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="导出范围">
              <el-radio-group v-model="exportForm.range">
                <el-radio label="all">全部数据</el-radio>
                <el-radio label="filtered">筛选数据</el-radio>
                <el-radio label="selected">选中数据</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导出格式">
              <el-select v-model="exportForm.format" placeholder="选择导出格式">
                <el-option label="Excel (.xlsx)" value="xlsx"></el-option>
                <el-option label="CSV (.csv)" value="csv"></el-option>
                <el-option label="PDF (.pdf)" value="pdf"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 筛选条件 -->
        <div v-if="exportForm.range === 'filtered'" class="filter-section">
          <h4>筛选条件</h4>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="资产分类">
                <el-select v-model="exportForm.category" placeholder="选择分类" clearable>
                  <el-option label="电子设备" value="电子设备"></el-option>
                  <el-option label="办公家具" value="办公家具"></el-option>
                  <el-option label="运输工具" value="运输工具"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="资产状态">
                <el-select v-model="exportForm.status" placeholder="选择状态" clearable>
                  <el-option label="正常" value="正常"></el-option>
                  <el-option label="维修中" value="维修中"></el-option>
                  <el-option label="报废" value="报废"></el-option>
                  <el-option label="闲置" value="闲置"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="购买日期">
                <el-date-picker
                  v-model="exportForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 字段选择 -->
        <el-form-item label="导出字段">
          <el-checkbox-group v-model="exportForm.fields">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-checkbox label="id">资产ID</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="name">资产名称</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="code">资产编码</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="categoryId">资产分类</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="status">资产状态</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="value">资产价值</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="location">位置</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="purchaseDate">购买日期</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="supplier">供应商</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="createdAt">创建时间</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="remark">备注</el-checkbox>
              </el-col>
            </el-row>
          </el-checkbox-group>
        </el-form-item>
        
        <!-- 导出选项 -->
        <el-form-item label="导出选项">
          <el-checkbox v-model="exportForm.includeHeader">包含表头</el-checkbox>
          <el-checkbox v-model="exportForm.includeSummary">包含汇总信息</el-checkbox>
          <el-checkbox v-model="exportForm.autoDownload">自动下载</el-checkbox>
        </el-form-item>
        
        <!-- 预览数据 -->
        <el-form-item label="数据预览">
          <el-button @click="previewData" type="primary" plain>预览数据</el-button>
          <span class="preview-tip">预计导出 {{ estimatedCount }} 条记录</span>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="startExport" :loading="exporting">
            开始导出
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 导出进度 -->
      <div v-if="exporting" class="export-progress">
        <el-progress 
          :percentage="exportProgress" 
          :status="exportProgress === 100 ? 'success' : ''"
        />
        <div class="progress-text">
          正在导出... {{ exportProgress }}%
        </div>
      </div>
      
      <!-- 导出历史 -->
      <div class="export-history">
        <h4>导出历史</h4>
        <el-table :data="exportHistory" style="width: 100%">
          <el-table-column prop="fileName" label="文件名" width="200"></el-table-column>
          <el-table-column prop="format" label="格式" width="100"></el-table-column>
          <el-table-column prop="recordCount" label="记录数" width="100"></el-table-column>
          <el-table-column prop="exportTime" label="导出时间" width="180"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                v-if="scope.row.status === '成功'" 
                type="text" 
                @click="downloadFile(scope.row)"
              >
                下载
              </el-button>
              <el-button type="text" @click="deleteHistory(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { assetApi } from '@/api'
import { AssetStatusTextToCode } from '@/utils/status'

const exportForm = ref({
  range: 'all',
  format: 'xlsx',
  category: '',
  status: '',
  dateRange: [],
  fields: ['id','name','code','categoryId','status','value','location','purchaseDate','supplier','createdAt','remark'],
  includeHeader: true,
  includeSummary: true,
  autoDownload: true
})

const exporting = ref(false)
const exportProgress = ref(0)

// 模拟导出历史数据
const exportHistory = ref([
  {
    fileName: '资产列表_20231201.xlsx',
    format: 'xlsx',
    recordCount: 156,
    exportTime: '2023-12-01 14:30:25',
    status: '成功'
  },
  {
    fileName: '资产统计_20231130.pdf',
    format: 'pdf',
    recordCount: 23,
    exportTime: '2023-11-30 16:45:12',
    status: '成功'
  }
])

const estimatedCount = computed(() => {
  if (exportForm.value.range === 'all') return 156
  if (exportForm.value.range === 'filtered') return 45
  return 10
})

const previewData = () => {
  ElMessage.success(`预览功能开发中，预计导出 ${estimatedCount.value} 条记录`)
}

const startExport = async () => {
  if (exportForm.value.fields.length === 0) {
    ElMessage.warning('请至少选择一个导出字段')
    return
  }

  exporting.value = true
  try {
    const params: any = {}
    if (exportForm.value.range === 'filtered') {
      if (exportForm.value.category) params.categoryId = exportForm.value.category
      if (exportForm.value.status) params.status = AssetStatusTextToCode[exportForm.value.status]
      if (exportForm.value.dateRange && exportForm.value.dateRange.length === 2) {
        params.startDate = exportForm.value.dateRange[0]
        params.endDate = exportForm.value.dateRange[1]
      }
    }
    const blob: any = await assetApi.export(params)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `资产列表_${new Date().toISOString().slice(0,10)}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    // 历史记录
    exportHistory.value.unshift({
      fileName: link.download,
      format: 'xlsx',
      recordCount: estimatedCount.value,
      exportTime: new Date().toLocaleString(),
      status: '成功'
    })

    ElMessage.success('导出完成！')
  } catch (err: any) {
    console.error(err)
    ElMessage.error(err?.message || '导出失败')
    exportHistory.value.unshift({
      fileName: '导出失败',
      format: 'xlsx',
      recordCount: 0,
      exportTime: new Date().toLocaleString(),
      status: '失败'
    })
  } finally {
    exporting.value = false
    exportProgress.value = 0
  }
}

const resetForm = () => {
  exportForm.value = {
    range: 'all',
    format: 'xlsx',
    category: '',
    status: '',
    dateRange: [],
    fields: ['id','name','code','categoryId','status','value','location','purchaseDate','supplier','createdAt','remark'],
    includeHeader: true,
    includeSummary: true,
    autoDownload: true
  }
}

const downloadFile = (record: any) => {
  ElMessage.success(`开始下载文件：${record.fileName}`)
}

const deleteHistory = (record: any) => {
  const index = exportHistory.value.indexOf(record)
  if (index > -1) {
    exportHistory.value.splice(index, 1)
    ElMessage.success('删除成功')
  }
}
</script>

<style scoped>
.asset-export {
  padding: 20px;
}

.export-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.export-form {
  margin-bottom: 30px;
}

.filter-section {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.filter-section h4 {
  margin: 0 0 15px 0;
  color: var(--text-color);
}

.preview-tip {
  margin-left: 10px;
  color: var(--text-color-secondary);
}

.export-progress {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.progress-text {
  margin-top: 10px;
  text-align: center;
  color: var(--text-color-secondary);
}

.export-history {
  margin-top: 30px;
}

.export-history h4 {
  margin: 0 0 15px 0;
  color: var(--text-color);
}

@media (max-width: 768px) {
  .asset-export {
    padding: 10px;
  }
  
  .filter-section {
    padding: 15px;
  }
  
  .el-form-item {
    margin-bottom: 15px;
  }
}
</style> 